package cn.reach.rpc.netty.client;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;

/**
 * 客户端处理器
 * 负责处理服务器返回的响应
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {
    private final NettyRpcClient client;
    
    public ClientHandler(NettyRpcClient client) {
        this.client = client;
    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try {
            String response = (String) msg;
            System.out.println("Received from server: " + response);
            
            // 假设响应格式为：futureId|response
            String[] parts = response.split("\\|", 2);
            if (parts.length == 2) {
                long futureId = Long.parseLong(parts[0]);
                client.received(futureId, parts[1]);
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}